<?php
/**
 * 有赞授权商品和订单管理
 * Author: lyun
 * Date: 2018/9/29
 * Created by Panxsoft.
 */

namespace App\Services\Youzan;



use App\Models\Concerns\YouzanAuthorizerable;
use App\Models\Customer\Customer;
use App\Models\Panx\Product;
use App\Models\Store\Store;
use App\Services\Repositories\Product\ProductRepository;
use Illuminate\Database\Eloquent\Collection;

class AuthorizerableService
{
    /**
     * 更新有赞商品和订单
     * @test
     *
     * @param YouzanAuthorizerable $customer_or_store
     * @param int $youzan_shop_id - 新授权的有赞（店铺）ID
     *
     * @return bool
     * @throws \Exception
     */
    public function deleteYouzanProductsAndOrders(YouzanAuthorizerable $customer_or_store,
                                                  int $youzan_shop_id): bool
    {
        $old_youzan_shop_id = $customer_or_store->youzanAuthorizer->youzan_store_id ?? null;
        if (is_null($old_youzan_shop_id)) {
            return false;
        }

        $is_same_shop = $old_youzan_shop_id === $youzan_shop_id;
        if ($is_same_shop) {
            return false;
        }

        // 清理有赞商品和订单
        $this->deleteYouzan($customer_or_store);

        return true;
    }

    /**
     * @param YouzanAuthorizerable $customer_or_store
     *
     * @throws \Exception
     */
    public function deleteYouzan(YouzanAuthorizerable  $customer_or_store)
    {
        // 清理有赞订单
        $this->deleteYouzanOrders($customer_or_store);

        // 清理有赞商品
        $this->deleteYouzanProducts($customer_or_store);
    }

    /**
     * @param YouzanAuthorizerable|Customer|Store $customer_or_store
     */
    private function deleteYouzanProducts(YouzanAuthorizerable $customer_or_store): void
    {
        /** @var Collection $youzan_products */
        $youzan_products = $customer_or_store->selfProducts()
            ->where('youzan_item_id', '<>', Product::NO_YOUZAN_ITEM_ID)
            ->get();

        $youzan_products->each(function(Product $youzan_product){
            ProductRepository::destroyCleanRelations($youzan_product);
        });
    }

    /**
     * @param YouzanAuthorizerable|Customer|Store $customer_or_store
     *
     * @throws \Exception
     */
    private function deleteYouzanOrders(YouzanAuthorizerable $customer_or_store): void
    {
        $customer_or_store->orders()->delete();
    }
}